package br.com.loteria.lotofacil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URL;
import java.util.zip.ZipFile;

public class FileResultadosLotofacil extends File {
	private static final long serialVersionUID = 1L;

	public FileResultadosLotofacil() {
		super("D_LOTFAC.HTM");
	}

	public FileResultadosLotofacil fazerDownload() throws IOException {
		CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

		URL url = new URL("http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_lotfac.zip");

		File fileZip = new File("D_lotfac.zip");

		try (InputStream inputStream = url.openStream()) {
			try (FileOutputStream fileOutputStream = new FileOutputStream(fileZip)) {
				int byteLido;
				while ((byteLido = inputStream.read()) > -1) {
					fileOutputStream.write(byteLido);
				}
			}
		}

		try (ZipFile zip = new ZipFile(fileZip)) {
			try (InputStream inputStream = zip.getInputStream(zip.getEntry(this.getName()))) {
				try (FileOutputStream fileOutputStream = new FileOutputStream(this)) {
					int byteLido;
					while ((byteLido = inputStream.read()) > -1) {
						fileOutputStream.write(byteLido);
					}
				}
			}
		}

		fileZip.deleteOnExit();

		return this;
	}
}